/*******************************************************************************
 * Copyright (c) 2008 L.Carbonnaux.
 *******************************************************************************/
package org.lcx.taskvision.core;

import java.util.HashMap;
import java.util.Map;

import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.Status;
import org.eclipse.mylyn.tasks.core.TaskRepository;
import org.eclipse.osgi.util.NLS;

import com.google.gdata.util.AuthenticationException;

/**
 * @author Laurent Carbonnaux
 */
public class TaskVisionClientManager {

	public TaskVisionClientManager() {
		super();
	}

	private Map<String, TaskVisionClient> clientByUrlUser = new HashMap<String, TaskVisionClient>();

	public synchronized TaskVisionClient getClient(TaskRepository repository) throws CoreException {
		try {
			String key = repository.getUrl() + ":" + repository.getUserName();
			TaskVisionClient client = clientByUrlUser.get(key);
			if (client == null) {
				client = TaskVisionClientFactory.createClient(repository);
				clientByUrlUser.put(key, client);
			}
			return client;
		} catch (AuthenticationException e) {
			throw new CoreException(new Status(Status.ERROR, TaskVisionCorePlugin.PLUGIN_ID, Status.ERROR,
					NLS.bind(Messages.ScrumVisionClientManager_invalid_credential, repository.getRepositoryLabel()), e));
		}
	}

	public void repositoriesRead() {
		// nothing
	}

	public void repositoryAdded(TaskRepository taskRepository) {
		String key = taskRepository.getUrl() + ":" + taskRepository.getUserName();
		clientByUrlUser.remove(key);
	}

	public void repositoryRemoved(TaskRepository taskRepository) {
		String key = taskRepository.getUrl() + ":" + taskRepository.getUserName();
		clientByUrlUser.remove(key);
	}

	public void repositorySettingsChanged(TaskRepository taskRepository) {
		String key = taskRepository.getUrl() + ":" + taskRepository.getUserName();
		clientByUrlUser.remove(key);
	}

}
